package cn.yotta.user.core.server.converter;

import cn.yotta.common.api.model.Paging;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author wyaoyao
 * @date 2023/3/16 13:15
 */
@UtilityClass
public class PageConvert {

    public static <R, T> Paging<R> convert(Page<T> page, Function<T, R> mapFunc) {
        if (Objects.isNull(page)) {
            return null;
        }
        final List<R> collect = page.getRecords().stream().map(mapFunc).collect(Collectors.toList());
        // Long total, List<T> data, Integer pageNo, Integer pageSize
        return new Paging<R>(page.getTotal(), collect, longCastToInt(page.getCurrent()), longCastToInt(page.getSize()));
    }

    /**
     * TODO：mybatisPlus返回的分页信息，使用的是Long类型
     */
    private static Integer longCastToInt(long current) {
        return Long.valueOf(current).intValue();
    }
}
